package com.iven.xie.encrypt.tool;


import com.iven.xie.encrypt.bean.EncryptBody;
import com.iven.xie.encrypt.config.EncryptBodyConfig;
import com.iven.xie.encrypt.enums.EncryptBodyMethod;
import com.iven.xie.encrypt.enums.SHAEncryptType;
import com.iven.xie.encrypt.exception.EncryptBodyFailException;
import com.iven.xie.encrypt.exception.EncryptMethodNotFoundException;
import com.iven.xie.encrypt.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * 响应数据的加密处理<br>
 *
 * @author iven.xie
 */
@Slf4j
@Component
public class EncryptResponseBodyService {

    @Autowired
    private EncryptBodyConfig config;

    /**
     * 选择加密方式并进行加密
     *
     * @param encryptBody 加密信息
     * @return 加密结果
     */
    public String switchEncrypt(EncryptBody encryptBody) {
        EncryptBodyMethod method = encryptBody.getEncryptBodyMethod();
        if (method == null) {
            throw new EncryptMethodNotFoundException();
        }
        if (method == EncryptBodyMethod.MD5) {
            return MD5EncryptUtil.encrypt(encryptBody.getFormatStringBody());
        }
        if (method == EncryptBodyMethod.SHA) {
            SHAEncryptType shaEncryptType = encryptBody.getShaEncryptType();
            if (shaEncryptType == null) {
                shaEncryptType = SHAEncryptType.SHA256;
            }
            return SHAEncryptUtil.encrypt(encryptBody.getFormatStringBody(), shaEncryptType);
        }
        if (method == EncryptBodyMethod.BASE64) {
            return BASE64EncryptUtil.encrypt(encryptBody.getFormatStringBody());
        }
        String key = encryptBody.getKey();
        if (method == EncryptBodyMethod.DES) {
            key = CheckUtils.checkAndGetKey(config.getDesKey(), key, "DES-KEY");
            return DESEncryptUtil.encrypt(encryptBody.getFormatStringBody(), key);
        }
        if (method == EncryptBodyMethod.AES) {
            key = CheckUtils.checkAndGetKey(config.getAesKey(), key, "AES-KEY");
            return AESEncryptUtil.encrypt(encryptBody.getFormatStringBody(), key);
        }
        if (method == EncryptBodyMethod.RSA) {
            key = CheckUtils.checkAndGetKey(config.getRsaPublicKey(), key, "RSA-PUBLIC-KEY");
            return RSAEncryptUtil.encrypt(encryptBody.getFormatStringBody(), key);
        }
        throw new EncryptBodyFailException();
    }


}
